<template>
  <div class="AssetAdd">
    <el-main>
      <el-row :gutter="20" style="1px solid #ccc">
        <el-col :span="4">
          <div class="grid-content bg-purple">
            <el-button type="primary">
              <router-link to="/CustomModule">自定义模板</router-link>
            </el-button>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="grid-content bg-purple">
            <!-- <el-upload
              class="upload-demo"
              action="http://wxtest.trfriend.com:12135/Upload/UploadAsset"
              :on-change="handleChange"
            >
              <el-button size="small" type="primary">
                <i class="el-icon-upload2"></i>
                批量导入资产
              </el-button>
            </el-upload>-->
            <el-button type="primary" @click="uploadAsset(innerVisible= true)">
              <i class="el-icon-upload2"></i>批量导入
            </el-button>
            <!-- 批量导入资产弹框 -->
            <el-dialog width="30%" title="批量导入资产" :visible.sync="innerVisible" append-to-body>
              <p>1.请选择自定义模块</p>
              <br>
              <el-select v-model="impotrtCustomTemplate" placeholder="请选择模块">
                <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
              <br>
              <br>
              <p>2.请按照数据模板的格式准备要导入的格式</p>
              <br>
              <el-button type="text" @click="downloadTemplate">下载数据模板</el-button>
              <br>
              <div>
                <h2>注意事项</h2>
                <p>1.模板中的表头名称不可更改,表头行不能修改;</p>
                <p>2.项目顺序不可以调整,不需要的项目可以不填写;</p>
                <p>3.其中资产分类,资产编码,资产名称,所属组织为必填项</p>
                <p>4.资产编码不可重复;</p>
                <p>5.导入的文件请勿超过1M.</p>
              </div>
              <br>
              <br>
              <div>
                <el-upload
                  ref="upload"
                  action="http://localhost:52112/Upload/UploadAsset"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :on-success="handleSuccess"
                  :file-list="fileList"
                  :auto-upload="false"
                >
                  <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                </el-upload>
              </div>
              <div slot="footer" class="dialog-footer">
                <el-button @click="innerVisible = false">取 消</el-button>
                <el-button type="text" size="small">
                  <el-button
                    style="margin-left: 10px;"
                    size="small"
                    type="success"
                    @click="submitUpload"
                  >开始导入</el-button>
                </el-button>
              </div>
            </el-dialog>
          </div>
        </el-col>
      </el-row>
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item></el-form-item>
        <el-form-item label="选择模块" prop="templateId">
          <el-select v-model="ruleForm.templateId" @change="consolelog" placeholder="通用模块">
            <el-option v-for="item in list" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <hr>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <el-form-item label="资产编号" prop="assetCode">
                <el-input v-model="ruleForm.assetCode" placeholder="资产编号必须是唯一的"></el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <el-form-item label="资产类别" prop="assetTypeId">
                <el-select
                  v-model="ruleForm.assetTypeId"
                  @change="consolelog1"
                  placeholder="资产类别"
                  style="width:237px;"
                >
                  <el-option
                    v-for="item in list1"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <el-form-item label="资产名称" prop="assetName">
                <el-input v-model="ruleForm.assetName" placeholder="请输入资产名称"></el-input>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <!-- <el-table-column prop="ownOrganizationName" label="所属公司" width="300"></el-table-column> -->
              <el-form-item label="所属公司" prop="ownOrganizationName">
                <el-input v-model="ruleForm.ownOrganizationName"></el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <el-form-item label="区域" prop="area">
                <el-input v-model="ruleForm.area" placeholder="请输入区域"></el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <el-form-item label="购入时间" prop="buyDate">
                <div class="block">
                  <el-date-picker
                    v-model="ruleForm.buyDate"
                    type="date"
                    placeholder="选择日期"
                    style="width:237px"
                  ></el-date-picker>
                </div>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <el-form-item label="规格型号" prop="standardType">
                <el-input v-model="ruleForm.standardType"></el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <el-form-item label="SN     号" prop="sn">
                <el-input v-model="ruleForm.sn"></el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <el-form-item label="计量单位" prop="unit">
                <el-input v-model="ruleForm.unit"></el-input>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <el-form-item label="金      额" prop="amount">
                <el-input v-model="ruleForm.amount" placeholder="单位(元)"></el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <el-form-item label="使用部门" prop="useOrganizationName">
                <el-input v-model="ruleForm.useOrganizationName"></el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <el-form-item label="存放地点" prop="storageLocation">
                <el-input v-model="ruleForm.storageLocation"></el-input>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <el-form-item label="使用期限">
                <el-input v-model="ruleForm.deadLine" placeholder="使用期限（月）" prop="deadLine"></el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <el-form-item label="使用人" prop="useUser">
                <el-input v-model="ruleForm.useUser"></el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <el-form-item label="来源" prop="ruleForm">
                <el-select v-model="ruleForm.region" style="width:237px">
                  <el-option label="购入" value="Buy"></el-option>
                  <el-option label="自建" value="SelfBuild"></el-option>
                  <el-option label="租赁" value="Rent"></el-option>
                  <el-option label="捐赠" value="Donate"></el-option>
                  <el-option label="内部购入" value="InternalPurchase"></el-option>
                  <el-option label="其他" value="Else"></el-option>
                </el-select>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <el-form-item label="备注" prop="remark">
                <el-input type="textarea" v-model="ruleForm.remark" style="width: 237px"></el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <el-form-item label="管理员" prop="assetAdmin">
                <el-input v-model="ruleForm.assetAdmin"></el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <el-form-item label="照片" prop="pictureUrl">
                <el-upload
                  class="avatar-uploader"
                  action="http://localhost:52112/Upload/UploadImage"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                >
                  <img v-if="imageUrl" :src="imageUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
            </div>
          </el-col>
        </el-row>

        <!-- 新增属性 -->
        <el-row>
          <el-col :span="8" v-for="item in assetExpandList" :key="item.key">
            <div class="grid-content bg-purple">
              <el-form-item :label="item.name" :id="item.key" prop="assetAdmin">
                <el-input v-model="item.value" style="width:237px"></el-input>
              </el-form-item>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="6" :offset="18">
            <div class="grid-content bg-purple">
              <el-button type="primary" @click="resetForm('ruleForm')">
                重置
                <!-- <router-link to="/AssetAdd"></router-link> -->
              </el-button>
              <el-button type="primary" @click="saveData(dialogVisible = true)">保存</el-button>
            </div>
            <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
              <span>
                <i class="el-icon-success" style="font-size:20px;margin:0 10px;"></i>保存成功,继续资产入库?
              </span>
              <span slot="footer" class="dialog-footer">
                <el-button @click="returnToAssetList">
                  <!-- <router-link to="/AssetList">资产列表</router-link> -->
                  资产列表
                </el-button>
                <el-button type="primary" @click=" addAnother">资产入库</el-button>
              </span>
            </el-dialog>
          </el-col>
        </el-row>
      </el-form>
    </el-main>
  </div>
</template>
<script>
import { axiosPost, axiosGet,requestUrl } from "@/api/index.js";
import { debug } from "util";
import { constants } from "crypto";
export default {
  data() {
    return {
      imageUrl: "",
      assetExpandList: [], //扩充字段
      ruleForm: {
        templateId: "",
        assetCode: "",
        assetTypeId: "",
        assetName: "",
        useOrganizationName: "",
        ownOrganizationName: "",
        area: "",
        remark: "",
        buyDate: "",
        standardType: "",
        sn: "",
        unit: "",
        amount: "",
        storageLocation: "",
        deadLine: "",
        useUser: "",
        from: "",
        assetAdmin: "",
        pictureUrl: "",
        remark: "",
        assetExpandList: ""
      },
      rules: {
        templateId: [
          { required: true, message: "通用模块", trigger: "change" }
        ],
        /* assetCode: [
          { required: true, message: "请输入资产编号", trigger: "blur" },
          { min: 3, max: 25, message: "长度在 3 到 25 个字符", trigger: "blur" }
        ], */
        assetTypeId: [
          { required: true, message: "请选择资产类别", trigger: "blur" }
        ],
        assetName: [
          { required: true, message: "请输入资产名称", trigger: "blur" }
        ],
        amount: [{ required: true, message: "请输入金额", trigger: "blur" }]
      },
      labelPosition: "right",
      dialogVisible: false,
      dialogTableVisible: false,
      dialogFormVisible: false,
      innerVisible: false, //导入资产弹框
      form: {
        PropertyName: "",
        PropertyType: "",
        date1: "",
        date2: "",
        delivery: false,
        type: [],
        resource: "",
        desc: ""
      },
      formLabelWidth: "120px",
      list: [],
      list1: [],
      options: [], //选择模块数组
      fileList: [],
      impotrtCustomTemplate: "",
      uploadFile: ""
    };
  },
  beforeMount() {
    //模块列表接口
    axiosGet("Asset/GetTemplateList", {
      userId: localStorage.getItem("userId")
    }).then(res => {
      if (res.status === 200 && res.data.success) {
        this.list = res.data.data;
      }
    });

    //资产类别接口
    axiosGet("Asset/GetAssetTypeList", {
      userId: localStorage.getItem("userId")
    }).then(res => {
      if (res.status === 200 && res.data.success) {
        this.list1 = res.data.data;
      } else {
      }
    });
  },
  created() {},
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          alert("submit!");
        } else {
          // console.log("error submit!!");
          return false;
        }
      });
    },
    //照片上传
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      // console.log(this.imageUrl);
      // console.log(res);
      console.log(res);
      this.ruleForm.pictureUrl = res.data.url;
      // console.log(this.ruleForm.pictureUrl);

      // console.log(file);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    //点击开始导入按钮事件
    submitUpload() {
      this.$refs.upload.submit();
    },
    //文件上传
    handleChange(file, fileList) {
      // console.log(file);
      this.fileList3 = fileList.slice(-3);
    },
    handleRemove(file, fileList) {
      var file1 = file;
      // console.log(file1);
    },
    handlePreview(file) {
      // console.log(file);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleSuccess(res) {
      // console.log(res);
      // console.log(this.impotrtCustomTemplate);
      if (res.success == true) {
        this.uploadFile = res.data.url;
        this.importFiles();
      }
    },

    consolelog() {
      //获取模板id  选中的某个模板的id
      // console.log(this.ruleForm.templateId);
      var bean = {
        templateId: this.ruleForm.templateId,
        userId: localStorage.getItem("userId")
      };
      axiosGet("Asset/GetProperty", bean).then(res => {
        if (res.status === 200 && res.data.success) {
          this.assetExpandList = res.data.data;
        }
      });
    },

    consolelog1() {
      // console.log(this.ruleForm.moudle);
    },
    //重置表格数据
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    returnToAssetList() {
      this.dialogVisible = false;
      this.$router.push({ name: "AssetList", params: {} });
    },

    //新增接口
    saveData() {
      var arr = [];
      this.assetExpandList.forEach(item => {
        arr.push({ key: item.key, value: item.value });
      });
      // console.log(arr);
      this.ruleForm.assetExpandList = JSON.stringify(arr);
      // console.log(this.ruleForm);
      axiosPost("Asset/AddAsset", this.ruleForm).then(res => {
        if (res.status === 200 && res.data.success) {
          // this.ruleForm = res.data.data;
          this.ruleForm = {};
          this.assetExpandList = [];
          this.$message({
            type: "success",
            message: "新增成功!"
          });
        }
      });
    },

    addAnother() {
      this.dialogVisible = false;
      this.$refs["ruleForm"].resetFields();
    },
    //上传资产
    /*  UploadAsset(){
      axiosPost("Upload/UploadAsset", this.ruleForm).then(res => {
        if (res.status === 200 && res.data.success) {
          // this.ruleForm = res.data.data;
        }
      });
    } */
    /*  addData(){
      axiosPost("Asset/AddAsset", this.ruleForm).then(res => {
        if (res.status === 200 && res.data.success) {
          this.ruleForm = res.data.data;
        }

        
      });
    }, */
    /* addProperty(){
      this.dialogFormVisible = false;
      let list=[];
      let obj={};
      if(!this.ruleForm.assetExpandList.length)
      {
        obj={key:"temp1",name:this.form.PropertyName};
         
      }else{
        list=this.ruleForm.assetExpandList.sort(this.compareAsc('key',4));
        let tempkey='temp'+(parseInt(list[list.length-1].key.substr(4,list[list.length-1].key.length))+1);
        obj={key:tempkey,name:this.form.PropertyName};
      }
       this.ruleForm.assetExpandList.push(obj);
      // var obj={key:"",value:this.form.PropertyName}
      console.log(this.ruleForm.assetExpandList);
    },
    compareAsc(property,index){//倒叙排序
        return function(a,b){
            var value1 = a[property];
            var value2 = b[property];
            return value1.substr(index,value1.length) - value2.substr(index,value2.length)  ;
        }
    } */
    //点击批量导入资产的时候调用模块列表接口
    uploadAsset() {
      //模块列表接口
      axiosGet("Asset/GetTemplateList", null).then(res => {
        if (res.status === 200 && res.data.success) {
          this.options = res.data.data;
        }
      });
    },

    importFiles() {
      var be = {};
      for (var i = 0; i < this.options.length; i++) {
        if (this.impotrtCustomTemplate == this.options[i].id) {
          be = this.options[i];
        }
      }

      var assetTypeId = be.assetTypeId;
      var templateId = be.templateId;
      var filePath = this.uploadFile;
      var bean = {
        assetTypeId: assetTypeId,
        templateId: templateId,
        filePath: filePath
      };
      axiosPost("/Asset/ImportAsset", bean).then(res => {
        if (res.status === 200 && res.data.success) {
          this.$message({
            showClose: true,
            message: "导入成功",
            type: "success"
          });
          this.$refs.upload.clearFiles();
        }
      });
    },
    //下载模板接口
    downloadTemplate() {
      var be = {};
      for (var i = 0; i < this.options.length; i++) {
        if (this.impotrtCustomTemplate == this.options[i].id) {
          be = this.options[i];
        }
      }

      var assetTypeId = be.assetTypeId;
      var templateId = be.templateId;

      window.location.href =
        requestUrl +
        "Asset/DownloadTemplate?assetTypeId=" +
        assetTypeId +
        "&templateId=" +
        templateId;
    }
  }
};
</script>

<style lang="scss" scoped>
.AssetAdd {
  height: 100%;
}
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>